package com.woshua.processkeepmodel;

import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;

public class RemoteService extends Service {

    private MyBinder binder;

    private RemoteConn remoteConn;

    @Override
    public void onCreate() {
        super.onCreate();
        binder=new MyBinder();

        if(remoteConn==null)
        {
            remoteConn=new RemoteConn();
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        bindService(new Intent(this,
                LocalService.class),remoteConn, Context.BIND_IMPORTANT);
        return START_STICKY;
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    private class MyBinder extends IProcessAidlInterface.Stub
    {

        @Override
        public String getServiceName() throws RemoteException {
            return "Remote Service";
        }
    }

    class RemoteConn implements ServiceConnection
    {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.e("LocalService","本地进程已经启动。。。");

            IProcessAidlInterface aidlInterface = IProcessAidlInterface.Stub.asInterface(service);

            try {
                Log.i("RemoteService", "connected with " + aidlInterface.getServiceName());
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
//            本地服务被干掉
            Toast.makeText(RemoteService.this,"本地链接断开，重新启动 LocalService",Toast.LENGTH_LONG)
                    .show();

            startService(new Intent(RemoteService.this,LocalService.class));
            bindService(new Intent(RemoteService.this,
                    LocalService.class),remoteConn, Context.BIND_IMPORTANT);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        unbindService(remoteConn);
    }
}
